package mn.slide.dailynews.tv;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;

import com.j256.ormlite.android.apptools.OpenHelperManager;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

import mn.slide.dailynews.R;
import mn.slide.dailynews.helper.DatabaseHelper;
import mn.slide.dailynews.tv.adapter.TvListAdapter;
import mn.slide.dailynews.tv.xml.parser.SaxHandler;

public class TvListActivity extends Activity
{
	private DatabaseHelper databaseHelper = null;
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		initdb();
		setContentView(R.layout.tvlist);
		ListView listView = (ListView) findViewById(R.id.tvListView);
		try
		{
			TvListAdapter adapter = new TvListAdapter(this, R.layout.tvlist_row, getHelper().getTvDao().queryForAll());
			listView.setAdapter(adapter);
		}
		catch (SQLException e)
		{
			e.printStackTrace();
		}
	}
	public void initdb(){
		
		try
		{
			SaxHandler saxHandler = new SaxHandler(this);
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser saxParser = factory.newSAXParser();
			
			InputStream inputStream = getAssets().open("tvguide.xml");
			saxParser.parse(inputStream, saxHandler);
		}
		catch (SAXException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		catch (ParserConfigurationException e)
		{
			e.printStackTrace();
		}
	}
	
	public DatabaseHelper getHelper() {
		if (databaseHelper == null)
			databaseHelper = OpenHelperManager.getHelper(this,
					DatabaseHelper.class);
		return databaseHelper;
	}
}